/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Struts2Utils.java 1211 2010-09-10 16:20:45Z calvinxiu $
 */
package com.levy.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.http.HttpServletResponse;

/**
 * Web工具类.
 * 
 * 实现获取Request/Response/Session与绕过jsp/freemaker直接输出文本的简化函数.
 * 
 * @author calvin
 */
public final class WebUtils {

	private static ObjectMapper mapper = new ObjectMapper();
	
	private static final Logger log = Logger.getLogger(WebUtils.class);
	
	private WebUtils() {
		
	}
	public static void renderJson(HttpServletResponse response, String content, String... headers) {
		initResponseHeader(response, headers);
		try {
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (Exception e) {
			log.info(e.getMessage(), e);
		}
	}
	
	
	/**
	 * 分析并设置contentType与headers.
	 */
	private static HttpServletResponse initResponseHeader(HttpServletResponse response, String... headers) {
		// 分析headers参数
		String encoding = "UTF-8";
		boolean noCache = true;
		for (String header : headers) {
			String headerName = StringUtils.substringBefore(header, ":");
			String headerValue = StringUtils.substringAfter(header, ":");

			if (StringUtils.equalsIgnoreCase(headerName,"encoding")) {
				encoding = headerValue;
			} else if (StringUtils.equalsIgnoreCase(headerName, "no-cache")) {
				noCache = Boolean.parseBoolean(headerValue);
			} else {
				throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}
		}

		// 设置headers参数
		String fullContentType =  "application/json;charset=" + encoding;
		response.setContentType(fullContentType);
		if (noCache) {
			setDisableCacheHeader(response);
		}

		return response;
	}
	
	/**
	 * 设置禁止客户端缓存的Header.
	 */
	public static void setDisableCacheHeader(HttpServletResponse response) {
		// Http 1.0 header
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		// Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
	}
	
	
	
}
